// 出库入库 公共云对像
const db = uniCloud.database();
const dbCmd = db.command;
const $ = dbCmd.aggregate;
const inStockCollection = db.collection("inStock");
const outStockCollection = db.collection("outStock");

// 获取数据库中所有的客户数据 聚合 数量 金额 已付金额（带分页）
exports.getOutStockManagerAggregatedData = async (customer_name, user_id, page = 1, pageSize = 10) => {
	try {
		let matchStage = {
			isDel: 0,
			user_id: user_id,
			status: {
				$nin: [2, 3]
			} // 只统计 status 不等于 2（已付清）和 3（退款）的记录
		};

		if (customer_name) {
			matchStage.customer_name = customer_name;
		}

		// 计算分页的 skip 值
		const skipCount = (page - 1) * pageSize;

		const result = await outStockCollection.aggregate()
			.match(matchStage)
			.group({
				_id: '$customer_name', // 分组依据，按客户名称 customer_name 分组
				totalPayableAmount: {
					$sum: '$payable_amount'
				}, // 总应付金额，累加所有订单的 payable_amount
				totalPaidAmount: {
					$sum: '$paid_amount'
				}, // 总已付金额，累加所有订单的 paid_amount
				orderCount: {
					$sum: 1
				}, // 订单数量，统计每个客户的订单总数
				customerPhone: {
					$first: '$customer_phone'
				}, // 客户电话，取该客户的第一条记录中的 customer_phone
				lastOrderDate: {
					$max: '$date'
				}, // 最近订单日期，取该客户所有订单中最晚的 date
				totalQuantity: {
					$sum: '$quantity'
				}, // 总销售数量，累加所有订单的 quantity
				totalNetProfit: {
					$sum: '$net_profit'
				}, // 总净利润，累加所有订单的 net_profit
				vehicleNumbers: {
					$addToSet: '$vehicle_number'
				} // 相关车号列表，收集所有订单的 vehicle_number 并去重
			})
			.project({
				customerName: {
					$ifNull: ['$_id', '未知客户']
				}, // 在 project 阶段处理空值
				totalPayableAmount: 1,
				totalPaidAmount: 1,
				unpaidAmount: {
					$subtract: [{
							$ifNull: ['$totalPayableAmount', 0]
						},
						{
							$ifNull: ['$totalPaidAmount', 0]
						}
					]
				},
				orderCount: 1,
				customerPhone: {
					$ifNull: ['$customerPhone', '']
				},
				lastOrderDate: 1,
				totalQuantity: 1,
				totalNetProfit: 1,
				vehicleNumbers: 1,
				_id: 0
			})
			.sort({
				totalPayableAmount: -1
			}) // 按总应付金额降序排序
			.skip(skipCount) // 跳过前面的记录
			.limit(pageSize) // 限制每页记录数
			.end();

		return {
			success: true,
			data: result?.data || [], // 确保返回空数组而不是 undefined
			message: '数据聚合成功'
		};
	} catch (error) {
		return {
			success: false,
			errorMessage: error.message,
			error: error
		};
	}
};


// 获取数据库中所有的入库数据，按厂商和规格聚合数量、金额和已付金额（带分页）
exports.getInStockManagerAggregatedData = async (manufacturer, specification, userId, page = 1, pageSize = 10) => {
	try {
		let matchStage = {
			isDel: 0, // 只查询未删除的记录
			userId: userId, // 按用户 ID 筛选，必须提供
			status: {
				$nin: [2]
			} // 只统计 status 不等于 2（已付清）
		};

		// 如果传入了 manufacturer，则添加筛选条件
		if (manufacturer) {
			matchStage.manufacturer = manufacturer;
		}
		// 如果传入了 specification，则添加筛选条件
		if (specification) {
			matchStage.specification = specification;
		}

		// 计算分页的 skip 值
		const skipCount = (page - 1) * pageSize;

		const result = await inStockCollection.aggregate()
			.match(matchStage) // 如果 matchStage 只有 isDel 和 userId，则匹配所有未删除记录
			.group({
				_id: {
					manufacturer: '$manufacturer', // 按厂商分组
					specification: '$specification' // 按规格分组
				},
				totalAmount: {
					$sum: '$totalAmount'
				}, // 总金额，累加所有入库记录的 totalAmount
				totalPaidAmount: {
					$sum: '$paidAmount'
				}, // 总已付金额，累加所有入库记录的 paidAmount
				recordCount: {
					$sum: 1
				}, // 入库记录数量，统计每组的记录总数
				totalQuantity: {
					$sum: '$quantity'
				}, // 总入库数量，累加所有入库记录的 quantity
				lastInStockDate: {
					$max: '$date'
				} // 最近入库日期，取该组所有记录中最晚的 date
			})
			.project({
				manufacturerName: {
					$ifNull: ['$_id.manufacturer', '未知厂商']
				}, // 从 _id 中提取厂商名
				specification: {
					$ifNull: ['$_id.specification', '未知规格']
				}, // 从 _id 中提取规格
				totalAmount: 1, // 总金额
				totalPaidAmount: 1, // 总已付金额
				remainingAmount: { // 剩余金额 = 总金额 - 已付金额
					$subtract: [{
							$ifNull: ['$totalAmount', 0]
						},
						{
							$ifNull: ['$totalPaidAmount', 0]
						}
					]
				},
				recordCount: 1, // 入库记录数量
				totalQuantity: 1, // 总入库数量
				lastInStockDate: 1, // 最近入库日期
				_id: 0 // 移除 _id 字段
			})
			.sort({
				totalAmount: -1
			}) // 按总金额降序排序
			.skip(skipCount) // 跳过前面的记录
			.limit(pageSize) // 限制每页记录数
			.end();

		return {
			success: true,
			data: result?.data || [], // 确保返回空数组而不是 undefined
			message: '入库数据聚合成功'
		};
	} catch (error) {
		return {
			success: false,
			errorMessage: error.message,
			error: error
		};
	}
};




//获取 outStock 中 status 为 0 或 1 且 isDel 为 0 的所有唯一 customer_name 集合

exports.fetchOutStockCustomerList = async (user_id) => {
	try {
		const result = await outStockCollection
			.aggregate()
			.match({
				isDel: 0, // 未删除
				user_id: user_id,
				status: {
					$nin: [2, 3]
				} // 只统计 status 不等于 2（已付清）和 3（退款）的记录
			})
			.group({
				_id: '$customer_name' // 按 customer_name 分组，去重
			})
			.project({
				_id: 0, // 不显示 _id
				customer_name: '$_id' // 将 _id 重命名为 customer_name
			})
			.end();
		return {
			success: true,
			data: result.data, // 返回去重后的 customer_name 列表
		};
	} catch (error) {
		return {
			success: false,
			error: error.message,
		};
	}
}


// 获取 inStock 中 status 为 0 或 1 且 isDel 为 0 的 manufacturer 和 specification 集合聚合
exports.fetchInStockMaterialSpecs = async (userId) => {
	try {
		const result = await inStockCollection
			.aggregate()
			.match({
				isDel: 0, // 未删除
				userId: userId, // 按用户 ID 筛选，必须提供
				status: {
					$nin: [2]
				} // 只统计 status 不等于 2（已付清）
			})
			.group({
				_id: {
					manufacturer: '$manufacturer', // 按 manufacturer 分组
					specification: '$specification' // 按 specification 分组
				}
			})
			.project({
				_id: 0, // 不显示 _id
				manufacturer: '$_id.manufacturer', // 提取 manufacturer
				specification: '$_id.specification' // 提取 specification
			})
			.end();

		return {
			success: true,
			data: result.data, // 返回去重后的 manufacturer 和 specification 组合列表
		};
	} catch (error) {
		return {
			success: false,
			error: error.message,
		};
	}
}


// 云函数名称: batchPaymentInStock
// 功能: 对 inStock 集合进行批量付款，按最早订单分配

exports.batchPaymentInStock = async (data, userId) => {
	const {
		paymentAmount,
		manufacturerName,
		specification,
		paymentDate
	} = data;
	if (!paymentAmount || paymentAmount <= 0) {
		return {
			success: false,
			message: '付款金额必须大于 0',
		};
	}
	if (!manufacturerName || !specification) {
		return {
			success: false,
			message: '厂商和规格 为必填参数',
		};
	}
	try {
		let remainingPayment = parseFloat(paymentAmount); // 转换为浮点数，确保计算准确
		const updatedRecords = []; // 存储更新后的记录

		// 获取 inStock 未完全支付的记录
		const inStockRes = await inStockCollection
			.aggregate()
			.match({
				manufacturer: manufacturerName, // 按厂商筛选
				specification: specification, // 按规格筛选
				isDel: 0, // 未删除
				userId: userId, // 按用户 ID 筛选
				status: {
					$nin: [2]
				} // 只统计 status 不等于 2（已付清）
			})
			.sort({
				date: 1
			}) // 按入库日期升序（最早的优先）
			.end();

		console.log(inStockRes, "===inStockRes===");
		// 处理记录
		const records = inStockRes.data.map((item) => ({
			id: item._id,
			date: item.date,
			totalAmount: item.totalAmount || 0,
			paidAmount: item.paidAmount || 0,
			remainingAmount: item.remainingAmount || item.totalAmount || 0,
		}));

		// 分配付款金额
		for (const record of records) {
			if (remainingPayment <= 0) break; // 付款金额用尽

			const unpaidAmount = record.totalAmount - record.paidAmount; // 未付金额
			if (unpaidAmount <= 0) continue; // 已付清，跳过

			const paymentToApply = Math.min(remainingPayment, unpaidAmount); // 本次分配金额
			const newPaidAmount = record.paidAmount + paymentToApply;
			const newRemainingAmount = record.totalAmount - newPaidAmount;
			const newStatus = newPaidAmount >= record.totalAmount ? 2 : (newPaidAmount > 0 ? 1 : 0);

			remainingPayment -= paymentToApply; // 更新剩余付款金额

			// 更新记录到数据库
			await inStockCollection.doc(record.id).update({
				// data: {
				// 	paidAmount: newPaidAmount,
				// 	remainingAmount: newRemainingAmount,
				// 	status: newStatus,
				// 	updateTime: paymentDate, // 更新时间
				// },
				paidAmount: newPaidAmount,
				remainingAmount: newRemainingAmount,
				status: newStatus,
				updateTime: paymentDate, // 更新时间
			});

			updatedRecords.push({
				id: record.id,
				date: record.date,
				paidAmount: newPaidAmount,
				remainingAmount: newRemainingAmount,
				status: newStatus,
			});
		}

		return {
			success: true,
			message: 'inStock 批量付款完成',
			updatedRecords, // 更新后的记录
			remainingPayment, // 剩余未分配的付款金额
		};
	} catch (error) {
		return {
			success: false,
			message: 'inStock 批量付款失败',
			error: error.message,
		};
	}
}


// 云函数名称: batchPaymentOutStock
// 功能: 对 outStock 集合进行批量付款，按最早订单分配

exports.batchPaymentOutStock = async (data, userId) => {
	const {
		paymentAmount,
		customerName,
		paymentDate
	} = data;
	if (!paymentAmount || paymentAmount <= 0) {
		return {
			success: false,
			message: '付款金额必须大于 0',
		};
	}
	if (!customerName) {
		return {
			success: false,
			message: '客户名称为必填参数',
		};
	}
	try {
		let remainingPayment = parseFloat(paymentAmount); // 转换为浮点数，确保计算准确
		const updatedRecords = []; // 存储更新后的记录

		// 获取 outStockRes 未完全支付的记录
		const outStockRes = await outStockCollection
			.aggregate()
			.match({
				customer_name: customerName, // 按客户姓名筛选
				isDel: 0, // 未删除
				user_id: userId, // 按用户 ID 筛选
				status: {
					$nin: [2, 3]
				} // 只统计 status 不等于 2（已付清）
			})
			.sort({
				date: 1
			}) // 按入库日期升序（最早的优先）
			.end();

		console.log(outStockRes, "===outStockRes===");
		// 处理记录
		const records = outStockRes.data.map((item) => ({
			id: item._id,
			date: item.date,
			totalAmount: item.payable_amount || item.amount || 0,
			paidAmount: item.paid_amount || 0,
			remainingAmount: (item.payable_amount || item.amount || 0) - (item.paid_amount || 0),
		}));
		// 分配付款金额
		for (const record of records) {
			if (remainingPayment <= 0) break; // 付款金额用尽

			const unpaidAmount = record.totalAmount - record.paidAmount; // 未付金额
			if (unpaidAmount <= 0) continue; // 已付清，跳过

			const paymentToApply = Math.min(remainingPayment, unpaidAmount); // 本次分配金额
			const newPaidAmount = record.paidAmount + paymentToApply;
			const newRemainingAmount = record.totalAmount - newPaidAmount;
			const newStatus = newPaidAmount >= record.totalAmount ? 2 : (newPaidAmount > 0 ? 1 : 0);

			remainingPayment -= paymentToApply; // 更新剩余付款金额

			// 更新记录到数据库
			await outStockCollection.doc(record.id).update({
				// data: {
				// 	paid_amount: newPaidAmount, // outStock 使用 paid_amount
				// 	status: newStatus,

				// },
				paid_amount: newPaidAmount, // outStock 使用 paid_amount
				status: newStatus,
				updateTime: paymentDate
			});

			updatedRecords.push({
				id: record.id,
				date: record.date,
				paidAmount: newPaidAmount,
				remainingAmount: newRemainingAmount,
				status: newStatus,
			});
		}

		return {
			success: true,
			message: '批量付款完成',
			updatedRecords, // 更新后的记录
			remainingPayment, // 剩余未分配的付款金额
		};
	} catch (error) {
		return {
			success: false,
			message: '批量付款失败',
			error: error.message,
		};
	}
}